import axios from 'axios';
import {createHashHistory} from 'history';
const history = createHashHistory();

let api = {
    //baseURL: 'http://47.96.138.140:8866/api/',
      baseURL: 'http://192.168.0.103:8808/api/',
};
axios.defaults.timeout = 50000;
axios.defaults.baseURL = api.baseURL;
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    config.headers.common['Authorization'] = window.localStorage.getItem('token');
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});


/**
 * get请求
 * @param url
 * @param params
 * @returns {Promise}
 */
export function fetch(url, params = {}) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params: params
        }).then(res => {
            if(res.data.status==='error'&&res.data.data.code===200){
                history.push('/login');
            }
            resolve(res.data)
        }).catch(err => {
            reject(err)
        })
    })
}

/**
 * post请求
 * @param url
 * @param params
 * @returns {Promise}
 */
export function post(url, params = {}) {
    return new Promise((resolve, reject) => {
        axios.post(url, params).then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err)
        })
    })
}
export function getBlob(url, params = {}) {
    return new Promise((resolve, reject) => {
        axios({
            method: 'GET',
            url: url,
            data: params,
            responseType: 'blob'
        }).then(response => {
            resolve(response.data);
        }).catch(err => {
            reject(err);
        });
    });
}
export function postBlob(url, params = {}) {
    return new Promise((resolve, reject) => {
        axios({
            method: 'POST',
            url: url,
            data: params,
            responseType: 'blob'
        }).then(response => {
            resolve(response.data);
        }).catch(err => {
            reject(err);
        });
    });
}

export default api;


